#!/usr/bin/env python
# coding: utf-8
import web
from config import settings,util
from config.settings import session
from datetime import datetime,timedelta
import hashlib

db = settings.db
render_login = web.template.render('templates/')
render = settings.render

class Index:
    def GET(self):
        require_login()
        #显示最近15天的每个监测站的四种主要指标的日均值数据曲线
        fist_date=datetime.now()+timedelta(days=-15)
        result = db.query("SELECT max(collection_date) AS last_date FROM v_site_day_data ")[0]
        if result:
            fist_date=result.last_date+timedelta(days=-15)
        #将查询结果转为list，可以多次遍历
        data_list =list(db.query("SELECT * FROM v_site_day_data  where collection_date>='"+fist_date.strftime("%Y-%m-%d")+"'"))
        stations=list(db.select('stations'))
        no2_line_name_dict,no2_chart_data_array=self.create_chart_data("avg_no2",stations,data_list)
        o3_line_name_dict,o3_chart_data_array=self.create_chart_data("avg_o3",stations,data_list)
        pm10_line_name_dict,pm10_chart_data_array=self.create_chart_data("avg_pm10",stations,data_list)
        pm25_line_name_dict,pm25_chart_data_array=self.create_chart_data("avg_pm25",stations,data_list)
        co_line_name_dict,co_chart_data_array=self.create_chart_data("avg_co",stations,data_list)
        so2_line_name_dict,so2_chart_data_array=self.create_chart_data("avg_so2",stations,data_list)

        #显示超标的数据
        value_dict,where_str=self.create_max_value_where_condition()
        data_list =db.query("SELECT * FROM v_site_hour_day_group_data  where "+where_str+" ")

        return render.index(data_list=data_list,no2_line_name_dict=no2_line_name_dict,o3_line_name_dict=o3_line_name_dict,pm10_line_name_dict=pm10_line_name_dict,\
                            pm25_line_name_dict=pm25_line_name_dict,co_line_name_dict=co_line_name_dict,so2_line_name_dict=so2_line_name_dict,no2_chart_data_array=util.two_array_to_utf_string(no2_chart_data_array),\
                            o3_chart_data_array=util.two_array_to_utf_string(o3_chart_data_array),pm10_chart_data_array=util.two_array_to_utf_string(pm10_chart_data_array),\
                            pm25_chart_data_array=util.two_array_to_utf_string(pm25_chart_data_array),co_chart_data_array=util.two_array_to_utf_string(co_chart_data_array),\
                            so2_chart_data_array=util.two_array_to_utf_string(so2_chart_data_array),value_dict=value_dict)

    def create_max_value_where_condition(self):
        where_str=""
        value_dict={}
        #查找参数最大值，构造where语句
        for key in util.data_type_title_dict:
            result=db.query("select max_value from alarms where field_name='%s' and state=true limit 1"%key)
            if result:
                max_value=result[0].max_value
                value_dict[key]=str(max_value)
                if where_str=="":#第一个条件不加 or关键字
                    where_str+=" %s>%d"%(key,max_value)
                else:
                    where_str+=" or  %s>%d"%(key,max_value)
            else:
                value_dict[key]=''
        return value_dict,where_str

    def create_chart_data(self,data_type,stations,data_list):
        #每个监测站生成一条曲线
        #按监测站、参数类型的组合方式来生成曲线
        data_array=[]
        line_dict={}
        i=0
        #从data list中取日期列表，去重并排序，,必须要考虑日期缺漏的情况，不同监测站的日期不一致怎么办
        x_date_array=util.get_date_sort_array_from_list(data_list)

        for station in stations:
            #先判断数据集里面是否有该监测站
            station_exist=util.is_station_in_data_list(station.name,data_list)
            if station_exist==False:
                print "%s not in data_list"%station.name
                continue
            short_name=station.name[0:2]
            title=short_name+util.data_type_title_dict[data_type]
            row_array=[]
            #生成某站点 在指定的日期范围内 某种监测类型的数据array
            for item in x_date_array:
                #在data_list中查找监测站名称、日期符合的记录，找到后返回指定数据列的值,没找到返回‘’
                #print "call util.query_site_date_type_value(station,item,data_type,data_list)(%s,%s,%s)"%(station.name,item,data_type)
                result_value=util.query_site_date_type_value(station.name,item,data_type,data_list)
                row_array.append(result_value)

            #如果全部都是‘’空值，说明没有这个监测站的数据
            if len(row_array)==0:
                continue
            #曲线编号和中文名称对应
            line_dict[data_type+"_%02d"%i]=title
            row_array.insert(0,title)
            data_array.append(row_array)
            i=i+1
        #为x轴数据加上开头字符串
        x_date_array.insert(0,"x_time_array")
        line_dict["line00"]="x_time_array"
        data_array.insert(0,x_date_array)
        #print data_array
        return line_dict,data_array

###登陆页面
class Login:  

    def GET(self): 
        if logged():  
            return 'You are logined.'  
        else:  
            return render_login.login(message='')  

    def POST(self):  
        postdata=web.input()  
        login_name=web.net.websafe(postdata.login_name)
        password=web.net.websafe(postdata.password)

        md5_password=hashlib.md5(password).hexdigest()
        user_result=db.query("select * from users where login_name='%s' and password='%s' limit 1"%(login_name,md5_password))
        if user_result:
            user=user_result[0]
            session.login_user_id=user.id
            session.username=user.user_name
            session.is_admin=user.is_admin
            print "session.login_user_id:%s"%session.login_user_id
            raise web.seeother('/')
        else:  
            return render_login.login(message=u'用户名及密码不正确') 

###注销登陆页面          
class Logout:  
    def GET(self):  
        session.login_user_id=0
        session.username=''
        session.is_admin=False
        session.kill()  
        raise web.seeother('/login')  

###判断用户是否登陆  
def logged():
    print "session.get%s"%session.get('login_user_id')
    if session.get('login_user_id')>0:
        return True
    else:  
        return False

def require_login():
    if logged()==False:
        raise web.seeother("/login")
        return

